/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ceair.flight.refund.util;

import com.ceair.flight.refund.location.dt.enums.CurrencyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 *
 * @author Colin_You
 */
public final class CurrencyUtil {

    private static final Logger LOG = LoggerFactory.getLogger(CurrencyUtil.class);

    public static BigDecimal getProfitableValue(String currency, double value) {
        return getProfitableValue(currency, String.valueOf(value));
    }

    public static BigDecimal getProfitableValue(String currency, String value) {
        return getProfitableValue(currency, new BigDecimal(value));
    }

    public static BigDecimal getProfitableValue(String currency, BigDecimal value) {
        return getNormalizeValue(currency, value, true);
    }

    public static BigDecimal getLossValue(String currency, double value) {
        return getProfitableValue(currency, String.valueOf(value));
    }

    public static BigDecimal getLossValue(String currency, String value) {
        return getProfitableValue(currency, new BigDecimal(value));
    }

    public static BigDecimal getLossValue(String currency, BigDecimal value) {
        return getNormalizeValue(currency, value, false);
    }

    public static BigDecimal getNormalizeValue(String currency, BigDecimal value, boolean isProfitable) {
        if (value == null) {
            return null;
        }
        CurrencyEnum enumValue = resolveByName(currency);
        if (isProfitable) {
            return value.setScale(enumValue.getScale(), enumValue.getProfitableMode());
        }
        return value.setScale(enumValue.getScale(), enumValue.getLossMode());
    }

    private static CurrencyEnum resolveByName(String currency) {
        CurrencyEnum enumValue = null;
        try {
            enumValue = CurrencyEnum.valueOf(currency);
        } catch (Exception e) {
            LOG.info("The scale of currecy {} not config", currency);
        }
        return enumValue != null ? enumValue : CurrencyEnum.NULL;
    }
}
